package com.droid.mvvmlib.base;

import java.lang.ref.WeakReference;

/**
 * 无分页Model
 * @author zyc0617
 * @since  2019/8/18 15:35
 */
public class BaseNonPagingModel<T> extends BaseModel<T> {

    protected void loadSuccess(T data, boolean isEmpty) {
        synchronized (this) {
            mUiHandler.postDelayed(() -> {
                for(WeakReference<IBaseModeListener> weakListner : mWeakLinkArrayList) {
                    if(weakListner.get() instanceof IModelListener) {
                        IModelListener listener = (IModelListener) weakListner.get();
                        if(listener != null){
                            listener.onLoadFinish(BaseNonPagingModel.this, data, isEmpty);
                        }
                    }
                }

                // 如果需要缓存数据，加载成功后缓存到preference中
                if(getCachedPreferenceKey() != null) {
                    saveToPreference(data);
                }

            },0);
        }
    }

    protected void loadFail(final String error) {
        synchronized (this) {
            mUiHandler.postDelayed(() -> {
                for(WeakReference<IBaseModeListener> weakListner : mWeakLinkArrayList) {
                    if(weakListner.get() instanceof IModelListener) {
                        IModelListener listener = (IModelListener) weakListner.get();
                        if(listener != null){
                            listener.onLoadFail(BaseNonPagingModel.this, error);
                        }
                    }
                }

            },0);
        }
    }


    @Override
    public void refresh() {

    }

    @Override
    protected void load() {

    }

    @Override
    protected void notifyCacheData(T data) {
        loadSuccess(data, false);
    }

    public interface IModelListener<T> extends IBaseModeListener {

        void onLoadFinish(BaseNonPagingModel model, T data, boolean isEmpty);
        void onLoadFail(BaseNonPagingModel model, String error);
    }
}
